package com.chase.champagne

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chase.champagne.data.ChampagneRecordViewModel
import com.chase.champagne.entity.ChampagneRecord
import com.chase.champagne.utils.formatDate
import com.chase.champagne.utils.formatTime
import com.chase.champagne.utils.showToast
import com.chase.champagne.utils.useDarkStatusBar
import com.github.gzuliyujiang.dialog.DialogConfig
import com.github.gzuliyujiang.dialog.DialogStyle
import com.github.gzuliyujiang.wheelpicker.TimePicker
import com.github.gzuliyujiang.wheelpicker.annotation.TimeMode
import com.github.gzuliyujiang.wheelpicker.widget.TimeWheelLayout
import com.haibin.calendarview.Calendar
import com.haibin.calendarview.CalendarView
import com.mylhyl.circledialog.CircleDialog
import java.lang.Exception
import java.util.Date
import java.text.SimpleDateFormat

class MainActivity : AppCompatActivity() {

    private lateinit var cpCalendarView: CalendarView
    private lateinit var cpRecyclerView: RecyclerView
    private lateinit var cpChampagneLayout: View
    private lateinit var cpChampagne: View
    private lateinit var cpChampagneHintText: TextView
    private lateinit var cpSelectedDayView: TextView

    private lateinit var cpCurrentDayHint: TextView
    private lateinit var cpCurrentDayLayout: View

    private lateinit var mainRVAdapter: MainRVAdapter

    private lateinit var cpEmptyLayout: View

    private lateinit var champagneRecordViewModel: ChampagneRecordViewModel

    private var selectedYear = -1
    private var selectedMonth = -1
    private var selectedDay = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        champagneRecordViewModel = ViewModelProviders.of(this).get(ChampagneRecordViewModel::class.java)

        cpCalendarView = findViewById(R.id.calendar_view_main)
        cpRecyclerView = findViewById(R.id.rv_main)
        cpChampagneLayout = findViewById(R.id.champagne_layout)
        cpChampagne = findViewById(R.id.champagne)
        cpChampagneHintText = findViewById(R.id.champagne_hint_text)
        cpSelectedDayView = findViewById(R.id.tv_month_day)

        cpCurrentDayHint = findViewById(R.id.tv_current_day)
        cpCurrentDayLayout = findViewById(R.id.fl_current)

        cpEmptyLayout = findViewById(R.id.empty_main)

        selectedYear = cpCalendarView.curYear
        selectedMonth = cpCalendarView.curMonth
        selectedDay = cpCalendarView.curDay

        useDarkStatusBar()

        initCPCalendarView()
        initCPRecyclerView()
        initCPChampagne()
        initCPs()

        champagneRecordViewModel.getLiveData().observe(this, Observer {
            champagneRecordViewModel.clearCache()
            mainRVAdapter.dataList = champagneRecordViewModel.getRecords(selectedYear, selectedMonth, selectedDay)
            mainRVAdapter.notifyDataSetChanged()
            updateEmpty()
        })
    }

    private fun updateEmpty() {
        if (mainRVAdapter.dataList.isEmpty()) {
            cpEmptyLayout.visibility = View.VISIBLE
        } else {
            cpEmptyLayout.visibility = View.GONE
        }
    }

    private fun initCPs() {
        cpCurrentDayHint.text = cpCalendarView.curDay.toString()
        cpCurrentDayLayout.setOnClickListener {
            cpCalendarView.scrollToCurrent(true)
//            cpCalendarView.run {
//                scrollToCalendar(curYear, curMonth, curDay, true, true)
//            }
        }
    }

    private fun onTimePicker(year: Int, month: Int, day: Int) {
        DialogConfig.setDialogStyle(DialogStyle.Three)
        val picker = TimePicker(this)
        picker.wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
        picker.setOnTimePickedListener { hour, minute, second ->
            val dateFormat2 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            val date = dateFormat2.parse("${formatDate(year, month, day)} ${formatTime(hour, minute, 0)}")
            val record = date?.let { ChampagneRecord(it, formatTime(hour, minute)) }
                ?:throw Exception()
            champagneRecordViewModel.addRecord(record)
        }
        picker.show()
    }

    private fun setSelectedDate(year: Int, month: Int, day: Int) {
        selectedYear = year
        selectedMonth = month
        selectedDay = day
    }

    private fun initCPChampagne() {
        cpChampagne.setOnClickListener {
            if (cpChampagneHintText.text == "补") {
                onTimePicker(selectedYear, selectedMonth, selectedDay)
            } else {
                val simpleDateFormat = SimpleDateFormat("HH:mm")
                val date =  Date(System.currentTimeMillis())
                val s = simpleDateFormat.format(date)

                val champagneRecord = ChampagneRecord(date, s)
                champagneRecordViewModel.addRecord(champagneRecord)

                // 标记
                val calendar = getCalendar(champagneRecord.year, champagneRecord.month, champagneRecord.day, "香槟")
                cpCalendarView.addSchemeDate(calendar)
            }
        }
    }

    private fun getCalendar(year: Int, month: Int, day: Int, text: String? = null) =
        Calendar().also {
            it.year = year
            it.month = month
            it.day = day
            text?.let { text -> it.scheme = text }
         }

    private fun initCPCalendarView() {
        cpSelectedDayView.text = "${cpCalendarView.curYear}年${cpCalendarView.curMonth}月"

        cpCalendarView.setOnCalendarSelectListener(object : CalendarView.OnCalendarSelectListener {
            override fun onCalendarSelect(calendar: Calendar?, isClick: Boolean) {
                calendar?.run {
                    selectedYear = year
                    selectedMonth = month
                    selectedDay = day

                    mainRVAdapter.dataList = champagneRecordViewModel.getRecords(selectedYear, selectedMonth, selectedDay)
                    mainRVAdapter.notifyDataSetChanged()

                    updateEmpty()

                    // 显示当前
                    cpSelectedDayView.text = "${selectedYear}年${selectedMonth}月"

                    // 之前之后现在
                    val curCalendar = cpCalendarView.run { getCalendar(curYear, curMonth, curDay) }
                    val selectedCalendar = getCalendar(year, month, day)

                    when {
                        selectedCalendar < curCalendar -> {
                            cpChampagneLayout.visibility = View.VISIBLE
                            cpChampagneHintText.text = "补"
                        }
                        selectedCalendar > curCalendar -> cpChampagneLayout.visibility = View.GONE
                        else -> {
                            cpChampagneLayout.visibility = View.VISIBLE
                            cpChampagneHintText.text = "开"
                        }
                    }
                }
            }

            override fun onCalendarOutOfRange(calendar: Calendar?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

        })
        val map = HashMap<String, Calendar>()
        champagneRecordViewModel.getLiveData().value?.forEach {
            val calendar = getCalendar(it.year, it.month, it.day, "香槟")
            map[calendar.toString()] = calendar
        }
        cpCalendarView.setSchemeDate(map)
    }

//    private val tempData = ArrayList<ChampagneRecord>().also {
//        val a = java.sql.Date(System.currentTimeMillis())
//        it.add(ChampagneRecord(a, "16:00"))
//        it.add(ChampagneRecord(a, "16:00"))
//    }

    private fun initCPRecyclerView() {
        cpRecyclerView.layoutManager = LinearLayoutManager(this)
        mainRVAdapter = MainRVAdapter(
            champagneRecordViewModel.getRecords(selectedYear, selectedMonth, selectedDay).also { Log.d("Chase-MainActivity", it.toString()) },
            MainRVAdapter.RInfo(
                rvLayout = R.layout.item_main_rv,
                time = R.id.time_item_main_ev
            )
        )

        mainRVAdapter.itemLongClickListener = { holder, position ->
            val record = mainRVAdapter.dataList[position]
            holder.itemView.setOnLongClickListener {
                CircleDialog.Builder()
                    .setRadius(20)
                    .setWidth(0.8f)
                    .setTitle("什么？你说你没开？")
                    .setText("\n删除${record.getFormatDate()}的记录\n")
                    .setPositive("删除") {
                        record.id?.let{ champagneRecordViewModel.removeRecordById(it) }
                    }
                    .setNegative("取消", null)
                    .show(supportFragmentManager)

                // LongClick的返回值为false表示只执行长按的事件
                // 为true表示执行完长按事件之后会执行点击事件OnClickListener
                false
                true
            }
        }

        cpRecyclerView.adapter = mainRVAdapter
    }
}
